package com.lxw.manage_cms.service;


import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

@Service
public class CmsGridFsServiceImpl implements ICmsGridFsService{

    @Autowired
    GridFsTemplate gridFsTemplate;
    @Autowired
    GridFSBucket gridFSBucket;

    @Override
    public ObjectId addTemplate(InputStream inputStream,String fileName) {

        ObjectId id = gridFsTemplate.store(inputStream, fileName);

        return id;

    }

    @Override
    public void delTemplate(String objectId) {

        gridFsTemplate.delete(Query.query(Criteria.where("_id").is(objectId)));
    }

    @Override
    public String queryContentById(String templateFileId) {
        //获取到储存桶中的元信息
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(templateFileId)));
        //获取到桶分片信息
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //合并信息
        GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);

        String tempStr = null;
        try {
            tempStr = IOUtils.toString(gridFsResource.getInputStream(),"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return tempStr;
    }
}
